import Koa from "koa";
import cors from "koa-cors";
import jwt from "koa-jwt";
import convert from "koa-convert";
import koaBody from "koa-body";
import logger from "koa-logger";

import "./src/model"; // 连接数据库
import { PORT, jwtSecret } from "./src/config/config.default";
import { errorHandler } from "./src/middleware/errorHandler";
import router from "./src/router";
const app = new Koa();

// 日志记录
app.use(logger());

// 错误处理
app.use(errorHandler);

// cors 跨域
app.use(convert(cors()));

// jwt 认证，除了login和register接口不需要
app.use(
  jwt({ secret: jwtSecret, key: "jwtdata" }).unless({
    path: [/^\/api\/login/, /^\/api\/register/]
  })
);

// 解析body
app.use(koaBody());

// 挂载路由
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(PORT, () => {
  console.info(`Server start is running at http://localhost:${PORT}`);
});
